#include "Library.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iomanip>

namespace library {

Library::Library(const std::string& filename) : filename(filename) {
    loadBooks();
}

void Library::loadBooks() {
    std::ifstream file(filename);
    if (!file) {
        std::cout << "创建新的图书数据文件\n";
        return;
    }

    books.clear();
    std::string line;
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string item;
        std::vector<std::string> items;
        
        while (std::getline(ss, item, ',')) {
            items.push_back(item);
        }

        // 打印每一行的解析结果
        std::cout << "解析行: ";
        for (const auto& item : items) {
            std::cout << item << " | ";
        }
        std::cout << std::endl;
        
        if (items.size() == 5) {
            books.emplace_back(
                std::stoi(items[0]),
                items[1],
                items[2],
                std::stoi(items[3])
            );
        }
    }
}

void Library::saveBooks() const {
    std::ofstream file(filename);
    if (!file) {
        std::cout << "无法保存到文件: " << filename << "\n";
        return;
    }
    for (const auto& book : books) {
        file << book.toString() << "\n";
    }
}

void Library::displayBooks() const {
    std::cout << "\n================================================================\n";
    std::cout << "| ID  |         书名          |    作者    |  总库存  | 当前库存 |\n";
    std::cout << "================================================================\n";

    for (const auto& book : books) {
        std::cout << "| " << std::left << std::setw(4) << book.getId() << "| "
                  << std::setw(20) << book.getName() << "| "
                  << std::setw(10) << book.getAuthor() << "| "
                  << std::right << std::setw(8) << book.getTotalStock() << " | "
                  << std::setw(8) << book.getCurrentStock() << " |\n";
    }
    
    std::cout << "================================================================\n";
}

bool Library::borrowBook(int id, int quantity) {
    for (auto& book : books) {
        if (book.getId() == id) {
            if (book.getCurrentStock() == 0) {
                std::cout << "《" << book.getName() << "》当前无库存，无法借出\n";
                return false;
            }
            if (book.borrow(quantity)) {
                saveBooks();
                std::cout << "成功借出 " << quantity << " 本《" << book.getName() << "》\n";
                return true;
            } else {
                std::cout << "库存不足，当前库存: " << book.getCurrentStock() << "\n";
                return false;
            }
        }
    }
    std::cout << "未找到ID为 " << id << " 的图书\n";
    return false;
}

bool Library::returnBook(int id, int quantity) {
    for (auto& book : books) {
        if (book.getId() == id) {
            if (book.returnBook(quantity)) {
                saveBooks();
                std::cout << "成功归还 " << quantity << " 本《" << book.getName() << "》\n";
                return true;
            } else {
                std::cout << "归还数量超过总库存，无法归还\n";
                return false;
            }
        }
    }
    std::cout << "未找到ID为 " << id << " 的图书\n";
    return false;
}

void Library::addBook(const std::string& name, const std::string& author, int stock) {
    int newId = 1;
    if (!books.empty()) {
        newId = std::max_element(books.begin(), books.end(),
            [](const Book& a, const Book& b) { return a.getId() < b.getId(); }
        )->getId() + 1;
    }
    
    books.emplace_back(newId, name, author, stock);
    saveBooks();
    std::cout << "成功添加新图书《" << name << "》\n";
}

bool Library::deleteBook(int id) {
    auto it = std::find_if(books.begin(), books.end(),
        [id](const Book& book) { return book.getId() == id; });
    
    if (it != books.end()) {
        std::cout << "确定要删除《" << it->getName() << "》吗？(y/n): ";
        char confirm;
        std::cin >> confirm;
        
        if (confirm == 'y' || confirm == 'Y') {
            books.erase(it);
            saveBooks();
            std::cout << "图书已删除\n";
            return true;
        }
    } else {
        std::cout << "未找到ID为 " << id << " 的图书\n";
    }
    return false;
}

bool Library::editBook(int id, const std::string& name, const std::string& author, int stock) {
    for (auto& book : books) {
        if (book.getId() == id) {
            book.setName(name);
            book.setAuthor(author);
            book.setTotalStock(stock);
            saveBooks();
            std::cout << "图书信息已更新\n";
            return true;
        }
    }
    std::cout << "未找到ID为 " << id << " 的图书\n";
    return false;
}

void Library::sortByStock() {
    std::sort(books.begin(), books.end(),
        [](const Book& a, const Book& b) {
            return a.getCurrentStock() < b.getCurrentStock();
        });
    saveBooks();
    std::cout << "图书已按当前存量排序（升序）\n";
    displayBooks();
}

void Library::showStatistics() const {
    std::cout << "\n================================================================\n";
    std::cout << "|                           统计信息                             |\n";
    std::cout << "================================================================\n";
    
    int totalBooks = 0;
    int availableBooks = 0;
    int borrowedBooks = 0;
    
    for (const auto& book : books) {
        totalBooks += book.getTotalStock();
        availableBooks += book.getCurrentStock();
    }
    borrowedBooks = totalBooks - availableBooks;
    
    std::cout << "|" << std::setw(20) << "总藏书数量: " 
              << std::setw(30) << totalBooks << " 本" 
              << std::setw(14) << "|\n";
    std::cout << "|" << std::setw(20) << "当前可借数量: " 
              << std::setw(30) << availableBooks << " 本" 
              << std::setw(14) << "|\n";
    std::cout << "|" << std::setw(20) << "借出数量: " 
              << std::setw(30) << borrowedBooks << " 本" 
              << std::setw(14) << "|\n";
    std::cout << "|" << std::setw(20) << "借出率: " 
              << std::setw(30) << std::fixed << std::setprecision(2) 
              << (totalBooks > 0 ? (borrowedBooks * 100.0 / totalBooks) : 0)
              << "%" << std::setw(14) << "|\n";
    
    std::cout << "================================================================\n";
    
    // 显示库存最少的图书
    std::cout << "\n库存最少的图书:\n";
    std::vector<Book> sortedBooks = books;
    std::sort(sortedBooks.begin(), sortedBooks.end(),
        [](const Book& a, const Book& b) {
            return a.getCurrentStock() < b.getCurrentStock();
        });
    
    int count = 0;
    for (const auto& book : sortedBooks) {
        if (count >= 3) break;
        std::cout << "* " << book.getName() << ": " 
                  << book.getCurrentStock() << " 本\n";
        count++;
    }
}

} // namespace library 